<?php
/*
 * This file is part of the overtrue/easy-sms.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Overtrue\EasySms\Gateways;

use Overtrue\EasySms\Contracts\GatewayInterface;
use Overtrue\EasySms\Contracts\MessageInterface;
use Overtrue\EasySms\Contracts\PhoneNumberInterface;
use Overtrue\EasySms\Exceptions\GatewayErrorException;
use Overtrue\EasySms\Support\Config;
use Overtrue\EasySms\Traits\HasHttpRequest;

/**
 * 牛信云
 * Class NxcloudGateway.
 *
 * @see https://www.nxcloud.com/document/sms/mt-sending-v2
 */
class NxcloudGateway extends Gateway
{
    use HasHttpRequest;

    const ENDPOINT_URL      = 'http://api2.nxcloud.com/api/sms/mtsend_v2';

    const ENDPOINT_FORMAT   = 'json';

    const ENDPOINT_METHOD   = 'mtsend';

    const ENDPOINT_BIZ_TYPE = '3';  // 业务类型 1 号码检测，2 whatsapp业务，3 短信，4 DID业务，5 隐私号，6 OTA，7 Viber，8 voice语音业务

    /**
     * @param PhoneNumberInterface $to
     * @param MessageInterface     $message
     * @param Config               $config
     *
     * @return array
     *
     * @throws GatewayErrorException;
     */
    public function send(PhoneNumberInterface $to, MessageInterface $message, Config $config)
    {
        $postData = array(
            "appKey"    => $config->get('appkey'),
            "phone"     => $to->getUniversalNumber() ,
            "content"   => $message->getContent($this)
        );
        $body       = json_encode($postData, JSON_UNESCAPED_UNICODE);
        $headersv2  = $this->BuildHeader($body);
        return $this->post($headersv2, $body);
    }



    public function post($headers,$body)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, self::ENDPOINT_URL);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        $result = curl_exec($ch); //获取发送结果
        curl_close($ch);
        $result = json_decode($result, true);
        return $result;
    }

    /**
     * 计算sign签名
     *
     * @param headers      请求头中的公共参数
     * @param body         body中json字符串
     * @param accessSecret 秘钥
     * @return
     */
    function calcSign($ts, $body) {
        // step1: 拼接header参数
        $str = "accessKey=".$this->config->get('accessKey')."&action=".self::ENDPOINT_METHOD
            ."&bizType=".self::ENDPOINT_BIZ_TYPE."&ts=".$ts;
        // step2: 拼接body参数
        if (!empty($body)) {
            $str = $str . "&body=" . $body;
        }
        $str = $str . "&accessSecret=".$this->config->get('AccessSecret');
        $ret = md5($str);
        return $ret;
    }

    /**
     *
     * 返回字符串毫秒时间戳
     * @return mixed|string
     */
    public function GetTotalMillisecond()
    {
        $time  = explode (" ", microtime () );
        $time  = $time [1] . ($time [0] * 1000);
        $time2 = explode ( ".", $time );
        $time  = $time2 [0];
        return $time;
    }

    /**
     * 请求头
     * @param $body
     * @return Array[]
     */
    public function BuildHeader($body)
    {
        $ts     = $this->GetTotalMillisecond();
        $sign   = $this->calcSign($ts, $body);
        $headers=[
            "accessKey:".$this->config->get('accessKey'),
            "ts:$ts",
            "bizType:3",
            "action:mtsend",
            "Content-Type:application/json",
            "sign:$sign"
        ];
        return $headers;
    }

}
